import axios from 'axios'
import ResultCode from './resultcode'
import { showNotify } from '@nutui/nutui'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import cfg from './config'
import { showToast } from '@nutui/nutui'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL + 'api',
  timeout: 30000
})

let toast: any = null

const showLoading = () => {
  toast = showToast.loading('加载中...')
}

const closeLoading = () => {
  if (toast) {
    toast.hide()
  }
}

service.interceptors.request.use(
  (config) => {
    showLoading()
    //set header
    const store = useAuthStore()
    config.headers.set({
      appkey: cfg.appkey,
      Authorization: 'Bearer ' + store.userToken
    })
    return config
  },
  (error) => {
    closeLoading()
    //show error
    showNotify.danger(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    closeLoading()
    const result = response.data
    console.log(result)
    if (result.code == ResultCode.SUCCESS) {
      return result
    } else {
      let msg = result.message
      if (result.errors) {
        msg += ':'
        result.errors.forEach((item: string[]) => {
          msg += item.join(',')
        })
      }
      showNotify.danger(msg)
      const router = useRouter()
      router.push({name: 'login'})
      return Promise.reject(result)
    }
  },
  (error) => {
    closeLoading()
    if (error.response && error.response.code == ResultCode.AUTH_ERROR) {
      //show error & redirect login
      showNotify.text(error.response.message, {
        type: 'danger',
        visible: true
      })
      const router = useRouter()
      router.push({name: 'login'})
    } else if (error.response && error.response.message) {
      //show error msg
      showNotify.danger(error.response.message)
    } else {
      //show error
      showNotify.danger(error)
    }
    return Promise.reject(error)
  }
)

export default service
